/**
 * Copyright (c) 2012 Nokia Corporation.
 */

package com.nokia.example.gfxsensorsdemo.engine;

import com.nokia.example.gfxsensorsdemo.sensors.AccelerationProvider;
import com.nokia.example.gfxsensorsdemo.sensors.AcclerationProviderListener;

/**
 * 
 */
public class MyModel implements AcclerationProviderListener {
	// Constants
	private static final float MAX_VELOCITY_PER_AXIS = 5.0f;
	private static final float FRICTION = 0.01f;
	
	// Members
	private AccelerationProvider _accelerationProvider = null;
    private final float[] _velocity;
    private final double[] _acceleration;

    /**
     * Constructor.
     */
    public MyModel() {
    	_velocity = new float[3];
    	_acceleration = new double[3];
    	
    	try {
    		_accelerationProvider = AccelerationProvider.getProvider(this);
    	}
    	catch (Exception e) {
    		System.out.println("Failed to construct acceleration provider!");
    		e.printStackTrace();
    	}
    	
    	for (int i = 0; i < 3; ++i) {
    		_velocity[i] = 1.0f;
    	}
    }
    
    /** 
     * @return
     */
    public float[] velocity() {
    	/*System.out.println(new Float(_velocity[0]).toString() + ", "
    			+ new Float(_velocity[1]).toString() + ", "
    			+ new Float(_velocity[2]).toString());*/
    	return _velocity;
    }

    /**
     * 
     * @return
     */
    public double[] acceleration() {
    	return _acceleration;
    }
    
    /**
     * 
     */
    public void calculateVelocity() {
    	float absVelocity;
    	
    	for (int i = 0; i < 3; ++i) {
    		_velocity[i] += _acceleration[i] / 100;
    		absVelocity = Math.abs(_velocity[i]);
    		
    		if (absVelocity >= FRICTION) {
    			_velocity[i] -= FRICTION * (_velocity[i] / absVelocity);
    		}
    		else {
    			_velocity[i] = 0;
    		}
    		
    		if (_velocity[i] < -MAX_VELOCITY_PER_AXIS) {
    			_velocity[i] = -MAX_VELOCITY_PER_AXIS;
    		}
    		else if (_velocity[i] > MAX_VELOCITY_PER_AXIS) {
    			_velocity[i] = MAX_VELOCITY_PER_AXIS;
    		}
    	}
    }

    /**
     * 
     */
	public void dataReceived(double ax, double ay, double az) {
		_acceleration[0] = ax;
		_acceleration[1] = ay;
		_acceleration[2] = az - 9.81;		
	}
}
